<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Type Ahead 👀</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>

  <form class="search-form">
    <input type="text" class="search" placeholder="City or State">
    <ul class="suggestions">
      <li>Filter for a city</li>
      <li>or a state</li>
    </ul>
  </form>
  <script>
    const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
    const cities = [];
    const Http = new XMLHttpRequest();
    Http.open("GET", endpoint);
    Http.send();

    Http.onreadystatechange = function () {
      if (this.readyState == 4 && this.status >= 200) {
        cities.push(...JSON.parse(Http.responseText));
      }
    }

    function findMatches(wordToMatch, cities) {
      return cities.filter(place => {
        // here we need to figure out if the city or state matches what was searched
        const regex = new RegExp(wordToMatch, 'gi');
        return place.city.match(regex) || place.state.match(regex)
      });
    }

    function displayMatches() {
      let matches = findMatches(this.value, cities);
      const html = matches.map(place => {
        const reg = new RegExp(this.value, "gi");
        const cityName = place.city.replace(reg, `<span class="hl">${this.value}</span>`);
        const stateName = place.state.replace(reg, `<span class="hl">${this.value}</span>`);
        return `
      <li>
        <span class="name">${cityName}, ${stateName}</span>
        <span class="population">${place.population}</span>
      </li>
    `;
      }).join('');
      suggestions.innerHTML = html;
    }
    const suggestions = document.querySelector(".suggestions");
    const iptVal = document.querySelector(".search");
    iptVal.addEventListener("input", displayMatches);
    iptVal.addEventListener("keyup", displayMatches);

  </script>
</body>

</html>